const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const { pool } = require('../config/database');

// JWT密钥
const JWT_SECRET = 'xiaotuxian_secret_key_2024';

// 判断是否为手机号的函数
function isMobileNumber(str) {
  const mobileRegex = /^1[3-9]\d{9}$/;
  return mobileRegex.test(str);
}

// 用户登录接口
router.post('/login', async (req, res) => {
  try {
    const { account, mobile, password } = req.body;
    
    // 获取登录标识符（手机号或账号）
    const loginIdentifier = mobile || account;
    
    if (!loginIdentifier || !password) {
      return res.json({
        code: '0',
        msg: '账号和密码不能为空',
        result: null
      });
    }

    // 判断输入是手机号还是账号，决定查询字段
    const isMobile = mobile ? true : isMobileNumber(loginIdentifier);
    const query = `
      SELECT id, account, mobile, avatar, nickname, gender, birthday, cityCode, provinceCode, profession, password
      FROM sys_user 
      WHERE ${isMobile ? 'mobile' : 'account'} = ?
    `;
    // console.log('查询SQL:', query);
    // console.log('查询参数:', [loginIdentifier]);

    const [rows] = await pool.execute(query, [loginIdentifier]);
    
    if (rows.length === 0) {
      return res.json({
        code: '0',
        msg: '账号或密码错误',
        result: null
      });
    }
    
    const user = rows[0];
    
    // 验证密码（明文比较）
    if (user.password !== password) {
      return res.json({
        code: '0',
        msg: '账号或密码错误',
        result: null
      });
    }
    
    // 生成JWT token
    const tokenPayload = {
      name: user.nickname,
      id: user.id.toString(),
      username: user.account
    };
    
    const token = jwt.sign(
      { sub: JSON.stringify(tokenPayload) },
      JWT_SECRET,
      { 
        expiresIn: '30d',
        algorithm: 'HS256'
      }
    );
    
    // 返回用户信息
    const result = {
      id: user.id.toString(),
      account: user.account,
      mobile: user.mobile,
      token: token,
      avatar: user.avatar,
      nickname: user.nickname,
      gender: user.gender,
      birthday: user.birthday,
      cityCode: user.cityCode || '',
      provinceCode: user.provinceCode || '',
      profession: user.profession
    };
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: result
    });
    
  } catch (error) {
    console.error('Login error:', error);
    res.json({
      code: '0',
      msg: '登录失败',
      result: null
    });
  }
});

// 获取相关商品推荐接口
router.get('/goods/relevant', async (req, res) => {
  try {
    const { limit = 4 } = req.query;
    
    // 查询推荐商品
    const query = `
      SELECT 
        p.id,
        p.name,
        p.desc_text as desc,
        p.price,
        p.picture,
        p.discount,
        p.orderNum
      FROM sys_product p
      WHERE p.status = 1
      ORDER BY p.orderNum DESC, p.id DESC
      LIMIT ?
    `;
    
    const [rows] = await pool.execute(query, [parseInt(limit)]);
    
    // 格式化数据
    const goods = rows.map(item => ({
      id: item.id.toString(),
      name: item.name,
      desc: item.desc || '',
      price: item.price.toString(),
      picture: item.picture,
      discount: item.discount ? item.discount.toString() : null,
      orderNum: item.orderNum
    }));
    
    res.json({
      code: '1',
      msg: '操作成功',
      result: goods
    });
    
  } catch (error) {
    console.error('Get relevant goods error:', error);
    res.json({
      code: '0',
      msg: '获取推荐商品失败',
      result: []
    });
  }
});

module.exports = router;